const { ccclass, property } = cc._decorator;

@ccclass
export default class Helloworld extends cc.Component {

    private serverURL: string = 'ws://192.168.61.129:8100/?d=pZGskM1itZ3LNf5AqTse9DqQsIGeCn6RmMa7Jxai9YtcyDsiH9rE%2Bw7FET7rxwKAvLSgE43YLZq%2FiSsBxcT2IPYPEsk6EqX%2BVwgv8cIsW5rqdK8T4uNA8Xc%2F4isfGK1s'
    // private serverURL: string = 'ws://localhost:8081';
    // private serverURL: string = 'ws://192.168.61.129:8081';
    private socket: WebSocket = null;

    start() {
        this.node.on(cc.Node.EventType.MOUSE_DOWN, (event) => {
            this.onClickSendButton();
        });
    }

    // 点击按钮发送数据给服务器
    onClickSendButton() {
        let data = 'Hello, Server!';
        this.sendWebSocketData(data);
    }

    // 开始调用
    protected onLoad(): void {
        this.initWebSocketConnection();
    }

    protected onDestroy(): void {
        this.closeWebSocketConnection();
    }

    // 初始化 WebSocket 连接
    initWebSocketConnection() {
        this.socket = new WebSocket(this.serverURL);

        this.socket.onopen = (event) => {
            console.log('WebSocket connected!');
            // 可以在此处发送初始数据到服务器
            this.sendWebSocketData('hello-nb');
        };

        this.socket.onmessage = (event) => {
            console.log('Received message: ', event.data);
        };

        this.socket.onerror = (error) => {
            console.error('WebSocket error: ', error);
        };

        this.socket.onclose = (event) => {
            console.log('WebSocket closed: ', event);
        };
    }

    // 发送数据到服务器
    sendWebSocketData(data) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            console.log(`---- ${data}`);
            this.socket.send(data as string);
        }
    }

    // 关闭 WebSocket 连接
    closeWebSocketConnection() {
        if (this.socket) {
            this.socket.close();
        }
    }
}
